<?php

namespace app\admin\controller\finance;

use app\common\controller\Backend;
use think\Db;
use think\Cache;
use app\common\model\Config;
use app\common\model\User;
use app\admin\model\Admin;
use services\WxwithdrawalService;

/**
 * 经纪人提现记录
 *
 * @icon fa fa-circle-o
 */
class WithdrawalMiddleman extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\UserWithdrawalLog;
        $this->view->assign("statusList", $this->model->getLogStatusList());
        $this->db2 = Db::connect(config('database.db2'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $where2 = 'user.user_type=3';
            $auth_group_access = $this->db2->name('auth_group_access')->alias('aga')->where(['aga.uid'=>$this->auth->id])->find();
            $groups = [];
            if ($auth_group_access['group_id']==3) { // 业务员
                $groups[] = $this->auth->id;
            } elseif ($auth_group_access['group_id']==5) { // 经理
                $groups[] = $this->auth->id;
                $admin = $this->db2->name('admin')->where(['leader'=>$this->auth->id])->find();
                foreach ($admin as $key => $value) {
                    $groups[] = $value['id'];
                }
            }
            if ($groups) {
                $where2 .= ' and middleman.salesman_admin_id in ('.implode(',', $groups).')';
            }
            if (isset($decode['salesman_admin_id'])) {
                $where2 .= ' and middleman.salesman_admin_id='.$decode['salesman_admin_id'];
            }
            if (isset($decode['nickname']) && $decode['nickname']) {
                $where2 .= ' and user.nickname like "%'.$decode['nickname'].'%"';
            }
            if (isset($decode['area']) && $decode['area']) {
                $where2 .= ' and user.area like "%'.$decode['area'].'%"';
            }
            if (isset($decode['mreal_name']) && $decode['mreal_name']) {
                $where2 .= ' and middleman.real_name like "%'.$decode['mreal_name'].'%"';
            }
            if (isset($decode['no']) && $decode['no']) {
                $where2 .= ' and middleman.no like "%'.$decode['no'].'%"';
            }
            if (isset($decode['phone']) && $decode['phone']) {
                $where2 .= ' and middleman.phone like "%'.$decode['phone'].'%"';
            }
            $list = $this->db2->name('user_withdrawal_log')
                    ->alias('user_withdrawal_log')
                    ->field('user_withdrawal_log.*,user.nickname,middleman.real_name as mreal_name,middleman.no,user.area,middleman.salesman_admin_id,middleman.phone')
                    ->join('chbc_user user','user_withdrawal_log.user_id=user.id','left')
                    ->join('chbc_middleman middleman','middleman.user_id=user.id','left')
                    ->where($where)
                    ->where($where2)
                    ->order('user_withdrawal_log.id DESC')
                    ->paginate($limit);
            $admin = $this->db2->name('auth_group_access')->alias('aga')->join('chbc_admin a','aga.uid=a.id')->where(['aga.group_id'=>['in',[1,3]]])->select();
            $nickname = [];
            foreach ($admin as $v) {
                $nickname[$v['id']] = $v['nickname'];
            }

            $list2 = $list->items();
            foreach ($list2 as &$row) {
                $row['salesman_admin_id'] = isset($nickname[$row['salesman_admin_id']])?$nickname[$row['salesman_admin_id']]:'';
                if (isset($nickname[$row['handel_admin_id']])) {
                    $row['handel_admin_id'] = $nickname[$row['handel_admin_id']];
                } else {
                    $row['handel_admin_id'] = '';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        $salesmanList = [];
        $salesman = $this->salesmanList();
        foreach ($salesman as $key => $value) {
            $salesmanList[$value['id']] = $value['nickname'];
        }
        $this->assignconfig(['salesmanList' => $salesmanList]);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $rows = $row;
        $rows['category'] = Config::getConfigValue('shop_category',$rows['category_no']);
        $rows['business_time'] = Config::getConfigValue('business_time',$rows['business_time_no']);
        $rows['salesman'] = '';
        if ($rows['salesman_admin_id']) {
            $rows['salesman'] = Admin::where('id',$rows['salesman_admin_id'])->value('nickname');
        }
        $this->view->assign("row", $rows);
        return $this->view->fetch();
    }
    
    /**
     * 同意
     */
    public function agree($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['log_status'] != '0') {
            $this->error(__('请不要重复审核！'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'log_status' => '1',
                    'handel_admin_id' => $this->auth->id,
                    'handel_time' => time(),
                ]);
                //冻结金额扣除
                $money = -1*$row->wallet;
                User::money($money, $row->user_id, '提现通过', $row->id, 1);
                // 转账操作
                $WxwithdrawalService = new WxwithdrawalService();
                $publickey = Cache::get('publickey');
                if (!$publickey) {
                    // 获取微信证书
                    $res = $WxwithdrawalService->certificates();
                    $certificates = json_decode($res,1);
                    $Aes = new \fast\AesUtil(config('xcx.mch_key'));
                    $associatedData = $certificates['data'][0]['encrypt_certificate']['associated_data'];
                    $nonceStr = $certificates['data'][0]['encrypt_certificate']['nonce'];
                    $ciphertext = $certificates['data'][0]['encrypt_certificate']['ciphertext'];
                    // 解析公钥
                    $publickey = $Aes->decryptToString($associatedData, $nonceStr, $ciphertext); 
                    Cache::set('publickey',$publickey,86400);
                }
                $unionid = User::where('id',$row['user_id'])->value('unionid');
                $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'h5'])->value('openid');
                if (!$openid) {
                    $this->error('经纪人需要h5授权一下');
                }
                //请求参数
                $data = [
                    'appid'=>config('wx_gzh.appid'),
                    'out_batch_no'=>strval($row['withdrawal_no']),
                    'batch_name' => '吃喝不愁外卖试吃经纪人提现',
                    'batch_remark' => '吃喝不愁外卖试吃经纪人提现',
                    'total_amount' => $row['wallet']*100,
                    'total_num' => 1,
                    'transfer_detail_list'=>[[
                        'out_detail_no' => strval($row['withdrawal_no']),
                        'transfer_amount'=>$row['wallet']*100,
                        'transfer_remark'=>'吃喝不愁外卖试吃经纪人提现',
                        'openid' => $openid,
                        'user_name' => $WxwithdrawalService->getEncrypt($row['real_name'],$publickey),
                    ]],
                    'notify_url' => config('domain').'/index/yunzhan/txNotify'
                ];  
                $res = $WxwithdrawalService->transfer($data);
                //array(3) {
                // ["batch_id"]=>
                // string(42) "131000604005301691086842023052421965293543"
                // ["create_time"]=>
                // string(25) "2023-05-24T18:45:33+08:00"
                // ["out_batch_no"]=>
                // string(12) "504836592107"
                // }

                if(!isset($res['create_time'])) {//批次受理失败
                    Db::rollback();
                    $this->error($res['message']);
                } else {
                    // 审核通过
                    $result = $row->allowField(true)->save([
                        'log_status' => 1,
                        'handel_admin_id' => $this->auth->id,
                        'handel_time' => time(),
                        'batch_id' => $res['batch_id'],
                    ]);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 拒绝
     */
    public function refuse($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['log_status'] = -1;
                    $params['handel_time'] = time();
                    $params['handel_admin_id'] = $this->auth->id;
                    $result = $row->allowField(true)->save($params);
                    
                    //冻结金额返还
                    $money = -1*$row->wallet;
                    User::money($money, $row->user_id, '提现驳回', $row->id, 1);
                    // 金额增加
                    User::money($row->wallet, $row->user_id, '提现驳回', $row->id, 0);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        // 状态参数过滤掉
        if (isset($filter['mreal_name'])) {
            unset($filter['mreal_name']);
        }
        if (isset($filter['no'])) {
            unset($filter['no']);
        }
        if (isset($filter['nickname'])) {
            unset($filter['nickname']);
        }
        if (isset($filter['area'])) {
            unset($filter['area']);
        }
        if (isset($filter['salesman_admin_id'])) {
            unset($filter['salesman_admin_id']);
        }
        if (isset($filter['phone'])) {
            unset($filter['phone']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

}
